package com.ns.core.utils;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONException;
import com.alibaba.fastjson2.JSONObject;
import com.ns.core.current.config.SymbolsMark;
import com.ns.core.current.config.SysConst;
import com.ns.core.utils.cache.RedisUtil;
import com.ns.core.utils.rsa.TokenUtil;
import com.ns.core.utils.sg.IpUtil;
import com.ns.core.utils.sg.ResultError;
import com.ns.core.vo.au.SsoUserVO;
import org.springframework.util.StringUtils;

import java.util.Objects;

/**
 * 工具类
 *
 * @author lw
 */
public class StpUtil {
    public static void logout(Long id) {
        RedisUtil.del(SysConst.TOKEN + SymbolsMark.AT + id);

    }

    /**
     * 当前admin
     *
     * @return account
     */
    public static SsoUserVO getCurUser() {
        String st = IpUtil.getRequest().getHeader(SysConst.TOKEN);
        if (StringUtils.hasText(st)) {
            try {
                JSONObject secureObj = TokenUtil.parseToken(st);
                return JSON.parseObject(secureObj.getString(SysConst.TOKEN), SsoUserVO.class);
            } catch (JSONException e) {
                throw new ResultError("TOKEN 获取用户信息失败！");
            }
        }
        return null;
    }


    /**
     * 获取用户id
     *
     * @return Long
     */
    public static Long getLoginUserId() {
        SsoUserVO currAdmin = getCurUser();
        if (Objects.nonNull(currAdmin)) {
            return currAdmin.getId();
        }
        return null;
    }

    /**
     * 获取服务id
     *
     * @return Long
     */
    public static Long getSid() {
        String sid = IpUtil.getRequest().getHeader(SysConst.CUR_SID);
        return Objects.nonNull(sid) ? Long.parseLong(sid) : null;
    }

    /**
     * 获取租户id
     *
     * @return Long
     */
    public static Long getRid() {
        SsoUserVO currAdmin = getCurUser();
        if (Objects.nonNull(currAdmin)) {
            return currAdmin.getRid();
        }
        return null;
    }

    /**
     * 登录缓存
     */

    public static void login(Long id, String token) {
        RedisUtil.set(SysConst.TOKEN + SymbolsMark.AT + id, token);
    }


    /**
     * 获取token
     *
     * @return String
     */
    public static String getTokenValue() {
        return IpUtil.getRequest().getHeader(SysConst.TOKEN);
    }
}
